package pb

import (
	"sort"
	"time"

	"github.com/XiaoMi/soar/advisor"
)

func NewLog(finger uint64, sql string, rulesMap map[string]advisor.Rule) *Log {
	rules := make([]*Rule, len(rulesMap))
	index := 0

	for _, rule := range rulesMap {
		rules[index] = &Rule{
			Item:     rule.Item,
			Severity: rule.Severity,
			Summary:  rule.Summary,
			Content:  rule.Content,
			Case:     rule.Case,
			Position: uint32(rule.Position),
		}

		index++
	}

	sort.Slice(rules, func(i, j int) bool {
		if rules[i].Severity == rules[j].Severity {
			return rules[i].Item > rules[j].Item
		}

		return rules[i].Severity > rules[j].Severity
	})

	return &Log{
		Finger:    finger,
		Rules:     rules,
		Sql:       sql,
		TimeStamp: time.Now().UnixMilli(),
		Count:     1,
	}
}
